package com.zoke.daycarpool.ui;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.zoke.daycarpool.R;
import com.zoke.daycarpool.base.BaseUi;
import com.zoke.daycarpool.config.CarpoolConfig;
import com.zoke.daycarpool.config.CarpoolParamStore;
import com.zoke.daycarpool.config.UrlBank;
import com.zoke.daycarpool.domain.Token;
import com.zoke.daycarpool.domain.UserBeen;
import com.zoke.daycarpool.domain.UserInstense;
import com.zoke.daycarpool.fragment.MainFragment;
import com.zoke.daycarpool.util.LogTest;
import com.zoke.support.http.HttpStores;
import com.zoke.support.http.ZokeErro;
import com.zoke.support.http.ZokeParams;
import com.zoke.support.utils.PersistTool;
import com.zoke.support.view.ZokeToast;

/**
 * 发布拼车
 * 
 * @author JackWu
 * @version
 * @date 2015-1-2
 * @_QQ_ 651319154
 */
public class Publish extends BaseUi {

	private TextView mStartTv;
	private TextView mEndTv;

	// private int mComeCode = 1;//

	private UserBeen mUser;

	private String mChannelId;// 频道id
	private int target = 1;// 1去北京 2 去香河 默认是去北京 --
	private String start;// 出发地点
	private String dest;// 目的地
	private String startLon;// 出发地经纬度
	private String startLat;//
	private String destLon;// 目的地经纬度
	private String destLat;//
	private String startTime;// 出发时间

	private String startCity;//
	private String destCity;//
	private String startCityCode;//
	private String destCityCode;//

	private View mPriceContainer;

	private boolean isTaker;// 是乘客？
	private TextView mChannelsTv;
	private EditText mPhoneEt;
	private EditText mPriceEt;
	private EditText mSeatsEt;
	private EditText mRemarkEt;
	private TextView mStartAdrss;
	private TextView mEndAdrss;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_publish);
		mTitleManager.setTitle("发布拼车").setLeftIcon(R.drawable.title_back);
		mEnableSwipeRight = true;
		mUser = UserInstense.getInstense(getApplicationContext()).getUser();
		isTaker = mUser.getIdentify().equals("1");
		findView();
		mPriceContainer.setVisibility(isTaker ? View.GONE : View.VISIBLE);
		setChannel();
		mPhoneEt.setText(mUser.getPhone());

	}

	// -- 设置channel
	private void setChannel() {
		startCity = PersistTool.getString(MainFragment.ChannelNameForStart,
				"北京");
		destCity = PersistTool.getString(MainFragment.ChannelNameForEnd, "香河");
		String mChannelName = startCity + CarpoolConfig.ROADARROW + destCity;
		mChannelId = PersistTool.getString(MainFragment.ChannelId, "1");
		mChannelsTv.setText("" + mChannelName);
		// 设置出发城市
		mStartTv.setText(destCity);
		mEndTv.setText(startCity);
		target = 1;
		startCityCode = PersistTool.getString(MainFragment.startCityCode, "");// 北京的code
		destCityCode = PersistTool.getString(MainFragment.endCityCode, "");// 香河的code

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data == null)
			return;
		if (resultCode == Channels.resultChannel) {
			setChannel();
			return;
		}
		//
		if (resultCode == LocationSearch.RESULTCODE_ADDRESS) {
			String addr = data.getStringExtra(LocationSearch.ADDRESS);
			String lat = data.getStringExtra(LocationSearch.ADD_LAT);
			String lng = data.getStringExtra(LocationSearch.ADD_LNG);
			if (requestCode == 12) {
				// 终点点击
				mEndAdrss.setText("" + addr);
				destLon = lng;
				destLat = lat;
			}

			if (requestCode == 13) {
				// 起点
				mStartAdrss.setText("" + addr);
				startLon = lng;
				startLat = lat;
			}
			LogTest.tag("经纬度=" + lat + ";" + lng);
			return;
		}
	}

	/** 发布 **/
	public void onClickPublish(View view) {
		fetchPublish();
	}

	@Override
	public void onSuccess(ZokeParams out) {
		super.onSuccess(out);
		String result = (String) out.getResult();
		LogTest.tag(result);
		try {
			JSONObject jo = new JSONObject(result);
			int code = jo.optInt("code");
			if (code == 0) {
				long token = jo.optLong("token");
				Token.getTokener().updateToken(token);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public boolean isCellphone(String str) {
		Pattern pattern = Pattern.compile("1[0-9]{10}");
		Matcher matcher = pattern.matcher(str);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}

	//

	public boolean isPrice(String price) {
		Pattern pattern = Pattern.compile("^[1-9]\\d*$");
		Matcher matcher = pattern.matcher(price);
		if (matcher.matches()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void onFails(ZokeParams out) {
		super.onFails(out);
		ZokeErro erro = (ZokeErro) out.getResult();
		LogTest.tag(erro.getErrorNo() + "");
	}

	private boolean checkParam() {
		String mobile = mPhoneEt.getText().toString().trim();
		// 校验手机号
		if (TextUtils.isEmpty(mobile)) {
			mPhoneEt.setError("手机号不能为空");
			return false;
		}
		if (!isCellphone(mobile)) {
			mPhoneEt.setError("请输入正确手机号");
			return false;
		}

		// 乘客不校验这个参数
		if (!isTaker) {
			String price = mPriceEt.getText().toString().trim();
			if (TextUtils.isEmpty(price)) {
				mPriceEt.setError("价格不能为空");
				return false;
			}

			if (!isPrice(price)) {
				mPriceEt.setError("请输入正确的价格");
				return false;
			}
			//
		}

		String seats = mSeatsEt.getText().toString().trim();
		if (TextUtils.isEmpty(seats)) {
			mSeatsEt.setError("拼车人数不能为空");
			return false;
		}

		if (!isPrice(seats)) {
			mSeatsEt.setError("请输入正确的拼车人数");
			return false;
		}

		return true;
	}

	/**  **/
	private void fetchPublish() {

		if (!checkParam())// 校验失败
			return;
		ZokeParams param = CarpoolParamStore.getDefaultParam(mHashCode);
		param.setUrl(UrlBank.doPublish);
		param.put("chId", mChannelId);// 先写死
		param.put("target", target + "");// 1 去北京 2去香河
		// 集成地址
		param.put("start", "香河物美");
		param.put("dest", "北京王府井");
		param.put("startLon", "111");
		param.put("startLat", "11");
		param.put("destLon", "111");
		param.put("destLat", "22");

		param.put("startTime", "2015-02-21 10:00");
		// 默认给1
		param.put("num", mSeatsEt.getText().toString().trim());
		if (!isTaker)
			param.put("price", mPriceEt.getText().toString().trim());// 使用Edit值
		param.put("mobile", mPhoneEt.getText().toString().trim());
		String remark = mRemarkEt.getText().toString().trim();
		if (!TextUtils.isEmpty(remark)) {
			param.put("remark", "" + remark);
		}
		param.put("sid", "" + mUser.getUserId());
		param.put("token", "" + Token.getTokener().getToken());
		HttpStores.getInstense(getApplicationContext()).find(param);
	}

	@Override
	protected void findView() {
		mStartTv = (TextView) findViewById(R.id.publish_start_tv);
		mEndTv = (TextView) findViewById(R.id.publish_end_tv);
		mPriceContainer = findViewById(R.id.price_Contaier);
		mChannelsTv = (TextView) findViewById(R.id.channels_TV);
		mPhoneEt = (EditText) findViewById(R.id.mobieEt);
		mPriceEt = (EditText) findViewById(R.id.priceEt);
		mSeatsEt = (EditText) findViewById(R.id.seatsEt);
		mRemarkEt = (EditText) findViewById(R.id.remarkEt);
		mStartAdrss = (TextView) findViewById(R.id.startaddressTv);
		mEndAdrss = (TextView) findViewById(R.id.endaddressTv);
	}

	/** 切换频道 **/
	public void onClickChange(View view) {
		if (target == 1) {
			// 改成去香河
			target = 2;
			mStartTv.setText(startCity);
			mEndTv.setText(destCity);
		} else {
			// 改成 -- 去北京 从香河出发 dest出发
			mStartTv.setText(destCity);
			mEndTv.setText(startCity);
			target = 1;
		}

	}

	/** 起点 **/
	public void onClickStart(View view) {
		mIntent = new Intent(this, LocationSearch.class);
		// target = 1 去北京
		String code = target == 1 ? destCityCode : startCityCode;
		mIntent.putExtra(LocationSearch.CITYCODE, code);
		startUIForResult(mIntent, 13);
	}

	/** 终点 **/
	public void onClickEnd(View view) {
		mIntent = new Intent(this, LocationSearch.class);
		String code = target == 1 ? startCityCode : destCityCode;
		mIntent.putExtra(LocationSearch.CITYCODE, code);
		startUIForResult(mIntent, 12);
	}

	/** 路线切换 **/
	public void onClickChannel(View view) {
		mIntent = new Intent(Publish.this, Channels.class);
		startUIForResult(mIntent, 11);
	}

}
